<template>
    <TopNav />

    <div class="main_wrap" style="background-color: #f5f5f5;padding: 0;">
        <div class="top">
            <template v-if="currentType === 0">
                <div class="row-between">
                    <div class="form_item">
                        <span class="label">调拨类型：</span>

                        <el-select popper-class="custom_select" v-model="currentType" placeholder="Select" size="large"
                            @change="changeCurrentType" style="width: 140px;margin-right: 20px">
                            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                        <el-button size="large" type="primary" @click="search">查询</el-button>
                    </div>
                    <el-button size="large" type="success" @click="newTransfer">新建调拨单</el-button>
                </div>

            </template>
            <template v-else>
                <div class="row">
                    <div class="form_item">
                        <span class="label">调拨类型：</span>

                        <el-select popper-class="custom_select" v-model="currentType" placeholder="Select" size="large"
                            @change="changeCurrentType" style="width: 140px;margin-right: 20px">
                            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>

                    <div class="form_item">
                        <span class="label">调拨日期：</span>
                        <el-date-picker v-model="strTime" ref="startTimeRef" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" :clearable="false" type="date" placeholder="请选择日期" size="large"
                            style="width: 200px;" />
                    </div>

                    <div style="margin-right:10px;">至</div>
                    <div class="form_item">

                        <el-date-picker v-model="endTime" ref="endTimeRef" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                            :clearable="false" type="date" placeholder="请选择日期" size="large" style="width: 200px;" />
                    </div>

                    <el-radio-group v-model="dayType" size="large" @change="changeDateTypes">
                        <el-radio-button label="今天" value="0" />
                        <el-radio-button label="昨天" value="1" />
                        <el-radio-button label="近7天" value="2" />
                    </el-radio-group>

                </div>

                <div class="row-between" style="padding: 10px 0;">
                    <div class="row">
                        <div class="form_item">
                            <span class="label">调拨店铺：</span>
                            <MyInput @click="onShopClick" placeholder="请选择店铺" :innerText="currentShop.name" />
                        </div>
                        <div class="form_item">
                            <span class="label">调拨商品：</span>
                            <MyInput @click="onGoodsClick" placeholder="请选择商品" :innerText="currentGoods.goodsName" />
                        </div>
                        <el-button size="large" @click="reset">重置</el-button>
                        <el-button size="large" type="primary" @click="search">查询</el-button>
                    </div>

                    <el-button size="large" type="success" @click="newTransfer">新建调拨单</el-button>
                </div>
            </template>



        </div>
        <div class="table_wrap" ref="myTableRef">
            <!-- :header-cell-style="{ backgroundColor: 'var(--ev-c-black)', color: '#fff' }" -->
            <el-table :header-cell-style="{ backgroundColor: 'var(--el-color-primary)', color: '#fff' }" stripe
                :data="currentPageTableData" @current-change="handleCurrentChange" highlight-current-row
                class-name="my_table">
                <el-table-column type="index" :index="indexMethod" width="50" />
                <el-table-column prop="allocationNumber" label="调拨单号" min-width="108" />
                <el-table-column :prop="currentType !== 1 ? 'outShopName' : 'enterShopName'" min-width="108"
                    :label="currentType !== 1 ? '调出店铺' : '调入店铺'" />
                <el-table-column prop="num" label="状态" min-width="76">
                    <template #default="scope">
                        <span :class="'status_' + scope.row.status">{{ scope.row.statusText }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="调拨日期" min-width="100" />
                <el-table-column prop="creatorName" label="调拨人" min-width="76" />
                <el-table-column label="操作" width="88" style="padding: 0;">
                    <template #default="scope">
                        <el-button type="primary" @click="openDesc(scope.row)">
                            详情
                        </el-button>

                    </template>
                </el-table-column>

            </el-table>
        </div>

        <div class="bottom_btns">

            <el-button size="large" type="primary" @click="prev" :disabled="currentPage == 1">上一页</el-button>

            <el-button size="large" type="primary" @click="next"
                :disabled="currentPage >= Math.ceil(pageTableData.flat().length / pageSize)">下一页</el-button>

        </div>
    </div>

    <!--搜索键盘 选择店铺-->
    <SearchKeyboard v-model="isShowShopSearchKeyboard" keyboardContainerClass="transferquery_shop_id"
        title="请输入店铺首字母搜索更多店铺" @onChange="onShopSearchKeyboardChange" class="custom_search_class">
        <CustomPaginate :list="filterShopList" @pageItemClick="chooseShop" style="margin-bottom: 5px;"/>
        
    </SearchKeyboard>
    <!--搜索键盘 选择商品-->
    <SearchKeyboard v-model="isShowGoodsSearchKeyboard" keyboardContainerClass="transferquery_goods_id"
        title="请输入商品首字母查询更多商品" @onChange="onGoodsSearchKeyboardChange" class="custom_search_class">
        <CustomPaginate :list="filterGoodsList" nameKey="goodsName" @pageItemClick="chooseGoods" style="margin-bottom: 5px;"/>
    </SearchKeyboard>
</template>

<script setup lang='ts'>
//@ts-nocheck
import pinyin from "pinyin";
import {  Search, ArrowLeftBold, ArrowRightBold } from '@element-plus/icons-vue'
import SearchKeyboard from '@renderer/components/SearchKeyboard.vue'
import CustomPaginate from '@renderer/components/CustomPaginate.vue'
import { ElMessage } from 'element-plus'
import { getDateTimeString } from '@renderer/utils'
import { ref, onMounted, watch, onActivated } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@renderer/store/user'
import { getUnreceiveTransferList, getOutTransferList, getInTransferList } from '@renderer/api/transferquery'
import { computed } from "vue";
import { useRouter } from "vue-router";

const typeOptions = ref([
    {
        label: '待接收调拨',
        value: 0
    },
    {
        label: '调拨出库',
        value: 1
    },
    {
        label: '调拨入库',
        value: 2
    }
])
const router = useRouter()
const shopKeywords = ref('') //搜索店铺关键字
const currentShopPageNo = ref(1) //当前搜索店铺页码
const goodsKeywords = ref('') //搜索商品关键字
const currentType = ref(0)
const pageTableData = ref([]) //分页后的数据
const userStore = useUserStore()
const { userInfo, shopInfo, saleGoodsData, shopList } = storeToRefs(userStore)
const shopID = shopInfo.value.shopID
const saleOrganizationID = userInfo.value.user_organizationId

//查询零售商品


function changeCurrentType() {

}

const tableData = ref([])
function handleCurrentChange() {

}
const pageSize = ref(1)
const myTableRef = ref()
const currentPage = ref(1)
const total = ref(0)
async function getUnreceiveData() {
    try {
        const { data } = await getUnreceiveTransferList(saleOrganizationID, shopID)
    tableData.value = data
    pageTableData.value = paginateData(data, pageSize.value)
    } catch (error) {
        console.log(error)
    }

}

onActivated(() => {
    console.log('onActivated!~')
    search()
})

onMounted(async () => {
    console.log('onMounted~~')


    console.log(myTableRef.value)
    let tableHeight = myTableRef.value.offsetHeight
    let singleRowHeight = 49 //每行高度
    pageSize.value = Math.floor(tableHeight / singleRowHeight) - 1 //每页最多显示行数(-1 是减去header)
    console.log(pageSize.value)

})

function prev() {
    if (currentPage.value <= 1) return
    currentPage.value--
}
function next() {
    if (currentPage.value >= pageTableData.value.length) return
    currentPage.value++
}

//计算序号
function indexMethod(index) {
    return (currentPage.value - 1) * pageSize.value + index + 1
}
//当前页数据
const currentPageTableData = computed(() => {
    return pageTableData.value[currentPage.value - 1]
})
const today = getDateTimeString(new Date().getTime())
const dayType = ref('0')
const strTime = ref(today)
const endTime = ref(today)

//日期改变后设置按钮组选中状态
watch([strTime, endTime], () => {
    setBtnsTypeByDate()
})

//今天、昨天、近7天切换
function changeDateTypes(val) {
    if (val === '0') {
        setToday()
    } else if (val === '1') {
        setYesterday()
    } else if (val === '2') {
        setLastWeek()
    }
}
function setToday() { //将日期设为今天
    const dateString = getDateTimeString(new Date().getTime())
    strTime.value = dateString
    endTime.value = dateString

}

function setYesterday() { //将日期设为昨天昨天
    const dateString = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24)
    strTime.value = dateString
    endTime.value = dateString

}
function setLastWeek() { //将日期设为近7天

    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
    const startDateString = getDateTimeString(new Date(start).getTime())
    strTime.value = startDateString
    endTime.value = getDateTimeString(new Date().getTime())
}

//根据日期设置按钮组选中状态
function setBtnsTypeByDate() {
    const todayStr = getDateTimeString(new Date().getTime())
    const yesterdayStr = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24)
    const lastWeekDayStr = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24 * 6)
    if (strTime.value === todayStr && endTime.value === todayStr) {
        dayType.value = '0'
    } else if (strTime.value === yesterdayStr && endTime.value === yesterdayStr) {
        dayType.value = '1'
    } else if (strTime.value === lastWeekDayStr && endTime.value === todayStr) {
        dayType.value = '2'
    } else {
        dayType.value = ''
    }
}


//搜索店铺
const isShowShopSearchKeyboard = ref(false)
const isShowGoodsSearchKeyboard = ref(false)
const currentShop = ref({
    name: '',
    id: ''
})
const currentGoods = ref({
    goodsName: ''
})
const filterShopList = computed(() => {
    return shopList.value.filter(item => {
        const pinyinItem = pinyin(item.name, {
            style: pinyin.STYLE_FIRST_LETTER //首字母模式
        }).join('')
        //  console.log(pinyinItem)   
        return pinyinItem.indexOf(shopKeywords.value) != -1
    })
})

const filterGoodsList = computed(() => {
    return saleGoodsData.value.filter(item => {
        const pinyinItem = pinyin(item.goodsName, {
            style: pinyin.STYLE_FIRST_LETTER //首字母模式
        }).join('')
        return pinyinItem.indexOf(goodsKeywords.value) != -1
    })
})
function onShopSearchKeyboardChange(val) {
    shopKeywords.value = val
}
function onGoodsSearchKeyboardChange(val) {
    goodsKeywords.value = val
}


function onShopClick() {
    isShowShopSearchKeyboard.value = true
}
function onGoodsClick() {
    isShowGoodsSearchKeyboard.value = true
}

function chooseShop(item) {
    currentShop.value = item
    shopKeywords.value = ''
    isShowShopSearchKeyboard.value = false
}
function chooseGoods(item) {
    currentGoods.value = item
    goodsKeywords.value = ''

    isShowGoodsSearchKeyboard.value = false
}
//重置查询条件
function reset() {
    currentShop.value = { name: '', id: '' }
    currentGoods.value = { goodsName: '' }
    setToday()
}


async function search() {

    if (strTime.value && endTime.value && new Date(endTime.value).getTime() < new Date(strTime.value).getTime()) {
        endTime.value = ''
        ElMessage({
            message: '结束时间不能小于开始时间',
            type: 'warning',
        })
        return
    }
    currentPage.value = 1

    const type = currentType.value
    const goodsName = currentGoods.value.goodsName

    if (type === 0) {
        await getUnreceiveData()

    } else if (type === 1) { //出库
        const enterShopID = currentShop.value.id

        const { data } = await getOutTransferList(saleOrganizationID, shopID, enterShopID, goodsName, strTime.value, endTime.value)
        tableData.value = data.content
        pageTableData.value = paginateData(data.content, pageSize.value)

    } else if (type === 2) {
        const outShopID = currentShop.value.id
        const { data } = await getInTransferList(saleOrganizationID, shopID, outShopID, goodsName, strTime.value, endTime.value)
        tableData.value = data.content
        pageTableData.value = paginateData(data.content, pageSize.value)
    }

}
//分页
function paginateData(data, pageSize) {
    console.log(data)
    const pages = [];
    for (let i = 0; i < data.length; i += pageSize) {
        pages.push(data.slice(i, i + pageSize));
    }
    console.log(pages)
    return pages;
}

function openDesc(row) {
    console.log(row)
    const status = row.status //0\1\2\3\4 (创建、待接收、接收、退回、撤回)
    if (status === 0 || status === 4 || status === 3 || status === 4) {
        router.push({ name: 'newtransfer', query: { row: JSON.stringify({ ...row, transferType: currentType.value }) } })
    }
    if (status === 1 || status=== 2) {
        router.push({ name: 'transferdesc', query: { row: JSON.stringify({ ...row, transferType: currentType.value }) } })
    }
}

function newTransfer() {
    router.push({ name: 'newtransfer' })
}
</script>
<style lang='scss' scoped>
.custom_select {

    .el-select-dropdown__item {

        line-height: 50px;
        height: 50px;

    }
}
</style>
<style lang='scss' scoped>
.custom_search_class {
    :deep(.search-keyboard-dialog) {
        left: 0;
        top: 160px;
        bottom: unset;
        width: 100%;
        box-sizing: border-box;
    }
}

.top {
    padding: 10px;
    background-color: #fff;

    .row-between {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .row {
        display: flex;
        align-items: center;


        .form_item {
            display: flex;
            align-items: center;
            margin-right: 10px;

            .label {
                width: 80px;

            }
        }

    }
}

.table_wrap {
    padding: 0 10px;
    height: calc(100% - 120px - 50px);
}

.bottom_btns {
    position: absolute;
    bottom: 5px;
    left: 10px;
}



//调拨单状态颜色  0\1\2\3\4 (创建、待接收、接收、退回、撤回)
.status_0 {
    color: var(--el-color-success);
}

.status_1 {
    color: var(--el-color-warning);
}

.status_2 {
    color: var(--el-color-primary);
}

.status_3 {
    color: var(--el-color-danger);
}

.status_4 {
    color: var(--el-color-info);
}
</style>